# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.template.loader import get_template
from mysite import models,forms
from django.template import RequestContext
from django.core.mail import EmailMessage
from django.contrib import messages
# from django.template import RequestContext

# Create your views here.
global username 
def index(request,vid=None,vpwd=None):
	if 'username' in request.session :
		username = request.session['username']
		useremail = request.session['useremail']
	template = get_template('index.html')
	html = template.render(locals())
	
	return HttpResponse(html)
	# template = get_template('index.html')
	# posts = models.Post.objects.filter(enabled=True).order_by('-pub_time')[:30]
	# moods = models.Mood.objects.all()
	# try:
		# user_id = request.GET['user_id']
		# user_pass = request.GET['user_pass']
		# user_post = request.GET['user_post']
		# user_mood = request.GET['mood']
	# except:
		# user_id = None
		# message = '如果要张贴信息，那么每一个字段都要填写……'
	
	# if vid and vpwd:
		# try:
			# post=models.Post.objects.get(id=vid)
		# except:
			# post=None
		# if post:
			# if post.del_pass==vpwd:
				# post.delete()
				# message = '删除成功！'
			# else:
				# message = '删除失败！'
	# elif user_id != None:
		# mood = models.Mood.objects.get(status=user_mood)
		# post = models.Post.objects.create(mood=mood,nickname=user_id,del_pass=user_pass,message=user_post)
		# post.save()
		# message='成功储存！请记得您的编辑密码[{}]！信息须审查后才会显示。'.format(user_pass)
		
	# html = template.render(locals())
	# return HttpResponse(html)
	
def login(request):
	if request.method == 'POST':
		login_form = forms.LoginForm(request.POST)
		if login_form.is_valid():
			login_name = request.POST['username'].strip()
			login_password = request.POST['password']
			try :
				user = models.User.objects.get(name = login_name)
				if user.password ==login_password:
					response = HttpResponseRedirect('/')
					request.session['username'] = user.name
					request.session['useremail'] = user.email
					request.session.set_expiry(120)
					messages.add_message(request,messages.SUCCESS,'成功登录了')
					return HttpResponseRedirect('/')
				else:
					messages.add_message(request,messages.ERROR,'密码错误，请检查密码是否与账号匹配')
			except:
				messages.add_message(request,messages.INFO,"没有当前用户，请<a href ='/regist'>注册</a>")
		else:
			messages.add_message(request,messages.WARNING,'请检查输入字段')
	else:
		login_form = forms.LoginForm()
	
	template = get_template('login.html')
	request_context = RequestContext(request)
	request_context.push(locals())
	html = template.render(context=locals(),request=request)
	response = HttpResponse(html)
	return response
	
	
def logout(request):
	response = HttpResponseRedirect('/')
	del request.session['username']
	return response
	
def userinfo(request):
	if 'username' in request.session:
		username = request.session['username']
	else:
		return HttpResponseRedirect('/login/')
	try:
		user = models.User.objects.get(name = username)
	except:
		pass
	template = get_template('userinfo.html')
	html = template.render(locals())
	return HttpResponse(html)
	
def posts(request):
	template = get_template('post.html')
	moods = models.Mood.objects.all()
	message='如果要张贴信息，那么每一个字段都要填写……'
	request_context = RequestContext(request)
	request_context.push(locals())
	# html = template.render(request_context)
	html = template.render(context=locals(),request=request)
	return HttpResponse(html)
	
def lists(request):
	template = get_template('lists.html')
	posts = models.Post.objects.filter(enabled=True).order_by('-pub_time')[:150]
	moods = models.Mood.objects.all()
	html = template.render(locals())
	return HttpResponse(html)
	
def contact(request):
	if request.method =='POST':
		form = forms.ContactForm(request.POST)
		if form.is_valid():
			user_name = form.cleaned_data['user_name']
			user_city = form.cleaned_data['user_city']
			user_school = form.cleaned_data['user_school']
			user_email = form.cleaned_data['user_email']
			user_message = form.cleaned_data['user_message']
			cnt = u'''
Dear {},
	your city is {} school is {} 
	message:{}'''.format(user_name,user_city,user_school,user_message)
			email=EmailMessage('test',cnt,'NieStore@163.com',[user_email])
			email.send()
			message = '感谢来信'
		else:	
			message = '请检查字段'
	else:
		form = forms.ContactForm()
	template = get_template('contact.html')
	request_context = RequestContext(request)
	request_context.push(locals())
	html = template.render(context=locals(),request=request)
	
	return HttpResponse(html)
	
def post(request):
	if request.method == 'POST':
		post_form = forms.PostForm(request.POST)
		if post_form.is_valid():
			message = '张贴成功，请等待管理员验证消息通过'
			post_form.save()
			return HttpResponseRedirect('/list')
		else:
			message = '张贴失败，请检查各字段'
	else:
		post_form = forms.PostForm()
		message = '如果要张贴信息，那么每一个字段都要填写……'
	template = get_template('post2db.html')
	moods = models.Mood.objects.all()
	message = '如果要张贴信息，那么每一个字段都要填写……'
	request_context = RequestContext(request)
	request_context.push(locals())
	html = template.render(context=locals(),request=request)
	
	return HttpResponse(html)